package com.woniu.controller;

import com.woniu.bean.UserVo;
import com.woniu.pojo.Dept;
import com.woniu.pojo.User;
import com.woniu.service.DeptService;
import com.woniu.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController{
    private Logger logger=Logger.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;

    @RequestMapping("/list")
    public ModelAndView userlist(UserVo userVo){
        logger.debug("----->");
        logger.debug(userVo.getAvailable());
        ModelAndView modelAndView=new ModelAndView();
        List<User> userList=userService.findUsersBypage(userVo);
        modelAndView.addObject("userlist",userList);
        modelAndView.addObject("uv",userVo);
        modelAndView.setViewName("/user/list.jsp");
        return modelAndView;
    }
    @RequestMapping(value = "/goAddUser")
    public ModelAndView goAddUser(){
        ModelAndView modelAndView=new ModelAndView();
        List<Dept> deptList=deptService.findAllDept();
        modelAndView.addObject("deptList",deptList);
        modelAndView.setViewName("/user/add.jsp");
        return modelAndView;
    }
    @RequestMapping(value = "/addUser")
    public String addUser(User user,HttpServletRequest request, @RequestParam("file")MultipartFile file){
        String realpath=request.getServletContext().getRealPath("/static/img/");
        logger.debug(realpath);
        String  imgPath=realpath+file.getOriginalFilename();
        logger.debug(imgPath);
        try {
            file.transferTo(new File(imgPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
//        logger.info("手机号:"+user.getTelephone());
//        logger.info("密码:"+user.getPassword());
//        logger.info("姓名:"+user.getRealname());
//        logger.info("生日:"+user.getBirthday());
//        logger.info("头像:"+user.getHeadimg());
//        logger.info("状态："+user.getAvailable());
//        logger.info("部门:"+user.getDept());
//        logger.info("部门id"+user.getDept().getId());
        user.setHeadimg("/static/img/"+file.getOriginalFilename());
        userService.addUser(user);
        return "list";
    }

}
